
using UnityEngine;


namespace KunURP {
    [ExecuteAlways]
    public class Water : MonoBehaviour
    {
        private static readonly int WaterRampMap = Shader.PropertyToID("_WaterRampMap"); 

        public Gradient absorptionRamp;
        public Gradient scatterRamp;

        private Texture2D m_RampTexture;

        private void OnValidate()
        {
            OnEnable();
        }

        private void OnEnable()
        {
            GenerateRampTexture();
        }

        private void OnDisable()
        {
            Dispose();
        }

        private void Dispose()
        {
            m_RampTexture = null;
        }

        private void GenerateRampTexture()
        {
            if (absorptionRamp == null || scatterRamp == null)
            {
                return;
            }
            if (m_RampTexture == null)
            {
                m_RampTexture = new Texture2D(128, 4, TextureFormat.ARGB32, false, false);
                m_RampTexture.wrapMode = TextureWrapMode.Clamp;
            }
            Color[] colors = new Color[512];
            for (int i = 0; i < 128; i++)
            {
                colors[i] = absorptionRamp.Evaluate((float)i / 128f);
            }
            for (int i = 0; i < 128; i++)
            {
                colors[i + 128] = scatterRamp.Evaluate((float)i / 128f);
            }
            m_RampTexture.SetPixels(colors);
            m_RampTexture.Apply();
            Shader.SetGlobalTexture(WaterRampMap, m_RampTexture);
        }
    }
}